package com.chapter2json.demo.service;

import com.chapter2json.demo.properties.FileStorageProperties;
import com.chapter2json.demo.exception.*;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@Service
public class FileStorageService {

    // 设置文件储存路径
    private final Path fileStorageLocation;

    public FileStorageService(FileStorageProperties fileStorageProperties) {
        this.fileStorageLocation = Paths.get(fileStorageProperties.getUploadDir())
                .toAbsolutePath().normalize();

        try {
            // 创建路径指定的文件夹，如果上传路径不存在，那么会创建这个目录
            if(!Files.exists(this.fileStorageLocation)) {
                Files.createDirectories(this.fileStorageLocation);
            }
        } catch (Exception ex) {
            throw new FileStorageException("Could not create the directory where the uploaded files will be stored.", ex);
        }
    }

    /**
     * 储存文件
     *
     * @param file 文件流对象
     * @return String 文件名 | Exception
     */
    public String storeFile(MultipartFile file) {
        // 规范化文件名
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());

        System.out.println(fileName);
        try {
            // 检查文件名是否包含无效字符
            if (fileName.contains("..")) {
                throw new FileStorageException("抱歉，文件名里面有无效字符 " + fileName);
            }

            // 得到上传目录上传文件对应的文件路径，保存在本地服务器的路径
            Path targetLocation = this.fileStorageLocation.resolve(fileName);
            // 复制文件到目标路径
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

            return fileName;
        } catch (IOException ex) {
            throw new FileStorageException("不能保存文件 " + fileName + ". 请重新尝试!", ex);
        }
    }

    /**
     * 加载文件资源
     *
     * @param fileName 文件名
     * @return Resource | Exception
     */
    public Resource loadFileResource(String fileName) {
        try {
            Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());
            if (resource.exists()) {
                return resource;
            } else {
                throw new FileNotFoundException("文件没找到 " + fileName);
            }
        } catch (MalformedURLException ex) {
            throw new FileNotFoundException("文件没找到 " + fileName, ex);
        }
    }
}